|
|
|
|
|
|
|
The hardest part of the error handling process is deciding what you want the application to do when the error occurs. Some errors can be fixed and the application can continue, whereas others require the application to close in order to fix them. Other errors might be ignored if they aren't detrimental to the application process. Before getting into the process of creating an error handler, lets take a look at a standard error handler in Visual Basic. Error handlers have three main parts to them: |
|
|
|
|
|
|
|
|
The On Error GoTo statement |
|
|
|
|
|
|
|
|
The On Error GoTo statement usually appears at the beginning of a routine and is used to enable the error-handling routine as shown. |
|
|
|
|
|
|
|
|
On Error GoTo CalcTotalError |
|
|
|
|
|
|
|
|
Every time an error occurs in the routine, the program will immediately pass control to the label CalcTotalError and begin executing the code that follows the label. Depending on the error and what process you want to perform, the error-handling code can be as simple or as complex as you need it to be. The simplest form of an error handler would just display the error number and description as shown in the following: |
|
|
|
|
|
|
|
|
MsgBox CStr(Err.Number) & - & Err.Description |
|
|
|
|
|
|
|
|
The third and final piece to this puzzle is the exit statement. This is the line of code that specifies where to go after the error handler has completed its work. Depending on how you want to exit the routine, you would use one of the three Resume statements or the Exit Sub or Exit Function to immediately exit the routine where the error occurred. The completed error-handling routine would look like the one in the following routine: |
|
|
|
|
|
|
|
|
Private Function CalcTotal(intQty as Integer, sngAmt as Single) as Single
On Error GoTo CalcTotal Error
CalcTotal = intQty * sngAmt
Exit Function
CalcTotalError:
MsgBox CStr(Err.Number) & - & Err.Description
End Function |
|
|
|
|
|
|
|
|
To see how to use the basic structure of an error-handling routine, start a new project in Visual Basic and add two text box and label controls and one command button to the default form, as shown in Figure 16.3. |
|
|
|
|
|